const express = require('express');
const router = express.Router();
const middleSession = require('../../middleware/middleSession')
const middleLogin = require('../../middleware/middleLogin')
const AccountModel = require('../../modules/AccountsModel');
router.post('/account',async (req,res)=>{
    await AccountModel.create({...req.body})
    res.json({
        code: 0,
        msg:'success',
        data: null
    })
})
router.get('/list',middleSession,async (req,res)=>{
    const data = await AccountModel.find() 
    res.json({
        code: 0,
        msg:'success',
        data
    })
})
router.delete('/del',middleSession,async (req,res)=>{
    const data = await AccountModel.deleteOne({_id: req.body.id}) 
    res.json({
        code: 0,
        msg:'success',
        data
    })
})
router.post('/reg',async (req,res)=>{ 
    const {username,password} = req.body 
    req.session.username = username
    req.session.password = password
    res.json({
        code: 0,
        msg:'success',
        data: null
    })
})
router.get('/logout',middleSession,async (req,res)=>{
    await req.session.destroy()
    res.json({
        code: 0,
        msg:'success',
        data: null
    })
    res.redirect('/login') 
})
router.post('/login',middleLogin, (req,res)=>{ 
    // res.json({
    //     code: 0,
    //     msg:'success',
    //     data: null
    // }) 
    res.redirect('/list')
})

module.exports = router;